# -*- coding: utf-8 -*-
from numpy import *
import operator
import os

# 构造训练数据集
def createDataSet():        
    group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])  
    labels = ['A','A','B','B']                          
    return group, labels

# k-邻近算法
def classify0(inX, dataSet, labels, k):     
    dataSetSize = dataSet.shape[0]                  # 读取训练集数据条数
    # 距离计算
    diffMat = tile(inX, (dataSetSize,1)) - dataSet  # 构造差矩阵，依次将输入数据与训练集数据做差
    sqDiffMat = diffMat**2                          # 对diffMat矩阵中的元素求平方
    sqDistances = sqDiffMat.sum(axis=1)             # axis=1，矩阵按行求和
    distances = sqDistances**0.5                    # 对sqDistances矩阵中的元素求平方根
    sortedDistIndicies = distances.argsort()        # 对distances中的元素值升序排列，返回其索引
    classCount={}
    for i in range(k):      # 选择距离最小的k个点，按label类型分类统计个数
        voteIlabel = labels[sortedDistIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
    # 排序
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]

# 将文本记录转化为NumPy的解析程序
def file2matrix(filename):              
    fr = open(filename)
    numberOfLines = len(fr.readlines())         # 获取文件行数
    returnMat = zeros((numberOfLines,3))        # 初始化returnMat矩阵
    classLabelVector = []                       # 初始化classLabelVector标签向量   
    fr = open(filename)
    index = 0
    for line in fr.readlines():
        line = line.strip()                 # 截取掉所有回车符
        listFromLine = line.split('\t')     # 用tab字符\t把整行数据分割成一个元素列表
        returnMat[index,:] = listFromLine[0:3]  # 取前三个元素放到returnMat矩阵中
        classLabelVector.append(int(listFromLine[-1]))  #取最后一列元素放到classLabelVector标签向量中
        index += 1
    return returnMat,classLabelVector

# 归一化特征值
def autoNorm(dataSet):
    minVals = dataSet.min(0)
    maxVals = dataSet.max(0)
    ranges = maxVals - minVals
    normDataSet = zeros(shape(dataSet))
    m = dataSet.shape[0]
    normDataSet = dataSet - tile(minVals, (m,1))
    normDataSet = normDataSet/tile(ranges, (m,1))   # 特征值相除
    return normDataSet, ranges, minVals

# 分类器针对约会网站的测试代码
def datingClassTest():
    hoRatio = 0.10      # hold out 10%
    datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')       # 载入数据集
    normMat, ranges, minVals = autoNorm(datingDataMat)
    m = normMat.shape[0]
    numTestVecs = int(m*hoRatio)
    errorCount = 0.0
    for i in range(numTestVecs):
        # 分类
        classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],3)
        print ("the classifier came back with: %d, the real answer is: %d" % (classifierResult, datingLabels[i]))
        if (classifierResult != datingLabels[i]): errorCount += 1.0
    print ("the total error rate is: %f" % (errorCount/float(numTestVecs)))
    print (errorCount)

# 将图像转换为测试向量    
def img2vector(filename):
    returnVect = zeros((1,1024))
    fr = open(filename)
    for i in range(32):
        lineStr = fr.readline()
        for j in range(32):
            returnVect[0,32*i+j] = int(lineStr[j])
    return returnVect

# 手写数字识别系统的测试代码
def handwritingClassTest():
    hwLabels = []       # 初始化手写数字分类标签向量hwLabels
    trainingFileList = os.listdir('digits/trainingDigits')     # 获取手写数字训练数据文本文件路径
    m = len(trainingFileList)                                  # 获取手写数字训练数据文本文件个数
    trainingMat = zeros((m,1024))                              # 初始化训练集trainingMat
    # 从文件名中解析分类数字，并将其保存在hwLabels中    
    for i in range(m):
        fileNameStr = trainingFileList[i]               # 依次读取文件名，例：'9_99.txt'
        fileStr = fileNameStr.split('.')[0]             # 截取.txt前的内容，例：'9_99'
        classNumStr = int(fileStr.split('_')[0])        # 截取_前的内容，例：9
        # hwLabels从右侧依次压入手写数字的分类标签
        hwLabels.append(classNumStr)
        # trainingMat依次将训练数据文件载入到矩阵中
        trainingMat[i,:] = img2vector('digits/trainingDigits/%s' % fileNameStr)
    testFileList = os.listdir('digits/testDigits')      # 获取手写数字测试数据文本文件路径
    errorCount = 0.0
    mTest = len(testFileList)                           # 获取手写数字测试数据文本文件个数
    # 从文件名中解析分类数字
    for i in range(mTest):
        fileNameStr = testFileList[i]                   # 依次读取文件名
        fileStr = fileNameStr.split('.')[0]             # 截取.txt前的内容
        classNumStr = int(fileStr.split('_')[0])        # 截取_前的内容
        vectorUnderTest = img2vector('digits/testDigits/%s' % fileNameStr)
        classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)
        print ("the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr))
        if (classifierResult != classNumStr): errorCount += 1.0
    print ("\nthe total number of errors is: %d" % errorCount)
    print ("\nthe total error rate is: %f" % (errorCount/float(mTest)))